import React from 'react';
import { 
  Modal,
  Form,
  Input,
  Col,
  // Select,
  Tree 
} from 'antd';

// const Option = Select.Option;
// const { TextArea } = Input;
const { TreeNode } = Tree;

const FormItem = Form.Item;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
};

const renderTreeNodes = data => data.map((item) => {
  if (item.childrenList) {
    return (
      <TreeNode title={item.name} key={item.id} dataRef={item}>
        {renderTreeNodes(item.childrenList)}
      </TreeNode>
    );
  }
  return <TreeNode title={item.name} key={item.id} dataRef={item} />;
});

class AddModal extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      value: [],
      authLists: []
    };
    this.flag = true;
    this.authList = [];
    this.onOK = this.onOK.bind(this);
  }

  componentDidMount(){
    const { authLists } = this.props;
    const $this = this;
    if (authLists.length && this.flag) {
      this.flag = false;
      const tree2Arr = (tree, parentIds) => {
        tree.forEach((item) => {
          item.parentIds = parentIds;
          $this.authList.push(item);
          if (item.childrenList) {
            tree2Arr(item.childrenList, [...parentIds, item.id.toString()]);
          }
        });
      };
      tree2Arr(authLists, []);
    }
  }

  componentWillReceiveProps(next) {
    const { roleMenuList } = next;
    if(roleMenuList !== this.props.roleMenuList){
      if (roleMenuList && roleMenuList.length) {
        const copyAuthList = [];
        roleMenuList.forEach((item) => {
          // if (item.opened) {
            copyAuthList.push(item.menuId.toString());
          // }
        });
        console.log(copyAuthList);
        this.setState({
          value: copyAuthList
        });
      }
    }
  }

  onOK () {
    const { onOK, form, onCancel, record, getList } = this.props;
    const { value } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        const params = { ...values, menuIds: value, id: record.id };
        onOK(params).then(() => {
          onCancel();
          getList();
        });
      }
    });
  }
  onCheck=(selectedKeys, even) => {
    let selectArr = [];
    const childrenIds = [];
    const selectNode = this.authList.filter(item => item.id === parseInt(even.node.props.eventKey, 0));
    this.authList.forEach((item) => {
      if (item.parentIds.indexOf(selectNode[0].key) !== -1) {
        childrenIds.push(item.key);
      }
    });
    if (even.checked) {
      selectArr = [...selectedKeys.checked, ...selectNode[0].parentIds, ...childrenIds];
    } else {
      selectArr = selectedKeys.checked.filter(item => childrenIds.indexOf(item) === -1);
    }
    const selectSet = new Set(selectArr);
    this.setState({
      value: [...selectSet]
    });
  }

  render () {
    const {
      onCancel, 
      form,
      loading, 
      record = {},
      authLists
   } = this.props;
    const { getFieldDecorator } = form;
    const modalOpts = {
      confirmLoading: loading,
      title: `${record.id ? '编辑' : '新增'}角色`,
      width: 800,
      visible: true,
      maskClosable: false,
      okText: '确定',
      cancelText: '取消',
      onOk: this.onOK,
      onCancel
    };
    const tProps = {
      value: this.state.value,
      onCheck: this.onCheck,
      checkable: true,
      // defaultExpandedKeys: this.state.value,
      checkStrictly: true,
      checkedKeys: this.state.value
    };
    return (
      <Modal {...modalOpts}>
        <Form className="clearfix myFormItem" >
          {record.id &&
          <Col span={12}>
            <FormItem
              {...layout}
              label="角色ID"
            >
              {getFieldDecorator('roleId', {
                initialValue: record.id,
                rules: [{ type: 'number' }]
              })(
                <Input disabled placeholder="请输入角色名称" />
              )}
            </FormItem>
          </Col>
          }
          <Col span={12}>
            <FormItem
              {...layout}
              label="角色名称"
            >
              {getFieldDecorator('name', {
                initialValue: record.name,
                rules: [{
                }]
              })(
                <Input disabled placeholder="请输入角色名称" />
              )}
            </FormItem>
          </Col>
          {/* <Col span={12}>
            <FormItem
              {...layout}
              label="状态"
            >
              {getFieldDecorator('enabled', {
                initialValue: record.enabled ? record.enabled.toString() : 'true'

              })(
                <Select>
                  <Option value="true">启用</Option>
                  <Option value="false">禁用</Option>
                </Select>
              )}
            </FormItem>
          </Col> */}
          {/* <Col span="24" >
            <FormItem
              label="角色描述"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
            >
              {getFieldDecorator('description', {
                initialValue: record.description
              })(
                <TextArea autosize={{ minRows: 3, maxRows: 8 }} placeholder="请简要说明" />
              )}
            </FormItem>

          </Col> */}
          <Col span="24" >
            <FormItem
              label="菜单权限"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
            >
              <div className="ant-input" style={{ height: '320px', overflow: 'scroll', border: '1px solid #ddd' }}>
                <Tree {...tProps} >
                  {renderTreeNodes(authLists)}
                </Tree>
              </div>
            </FormItem>

          </Col>
        </Form>
      </Modal>
    );
  }
}

export default Form.create()(AddModal);
